"""
Task 2.3: Handle Errors in API Requests

Goal: Learn to handle common API errors including 404s, timeouts, and invalid JSON.

Exercises:
- Handle 404 errors
- Handle timeout errors
- Handle invalid JSON responses
"""

import httpx
import json

# Exercise 3.1: Handle 404 errors
url = "https://jsonplaceholder.typicode.com/posts/9999"
# TODO: Send GET request and handle 404 error

response = httpx.get(url)

if response.status_code == 200:
    data = response.json()
    print("success:", data)
elif response.status_code == 404:
    print("the content does not exist")
    print(f"the status code:{response.status_code}")
    print(f"the url:{response.url}")
    print(f"the content:{response.text}")
else:
    print(f"another erorr:{response.status_code}")


    

# Exercise 3.2: Handle timeout errors
# TODO: Send GET request with a very short timeout and catch timeout exception


from httpx import TimeoutException

try:
    # 设置很短的超时时间（0.1秒）
    response = httpx.get(url, timeout=0.1)
    print("请求成功完成")
    
except TimeoutException:
    print("超时错误: 服务器响应太慢")
    print("可能的原因:")
    print("  1. 你的网络连接慢")
    print("  2. 服务器负载高，处理慢")
    print("  3. 超时时间设置得太短")
    print("解决方案:")
    print("  - 增加超时时间: timeout=30.0")
    print("  - 检查网络连接")
    print("  - 实现重试机制")
    

# Exercise 3.3: Handle invalid JSON responses
url = "https://jsonplaceholder.typicode.com/posts"
# TODO: Try parsing JSON and handle invalid JSON errors


print("=== 处理无效 JSON 响应 ===")

try:
    # 发送请求
    response = httpx.get(url)
    
    # 检查HTTP状态码
    if response.status_code == 200:
        print("✅ HTTP请求成功，开始解析JSON...")
        
        try:
            # 尝试解析JSON
            data = response.json()
            print("✅ JSON解析成功!")
            print(f"获取到 {len(data)} 条帖子")
            
            # 显示前3条数据作为示例
            for i, post in enumerate(data[:3]):
                print(f"  帖子 {i+1}: ID={post['id']}, 标题={post['title'][:30]}...")
                
        except json.JSONDecodeError as e:
            print("❌ JSON解析错误: 服务器返回了无效的JSON格式")
            print(f"   错误详情: {e}")
            print(f"   错误位置: 第{e.lineno}行, 第{e.colno}列")
            print(f"   响应类型: {response.headers.get('content-type', '未知')}")
            print("   实际响应内容前200字符:")
            print(f"   {response.text[:200]}...")
            
        except Exception as e:
            print(f"❌ 其他解析错误: {e}")
            
    else:
        # 处理非200状态码
        print(f"❌ HTTP错误，状态码: {response.status_code}")  # ✅ 修复了这里的打印
        print(f"   错误信息: {response.text}")
        
except httpx.RequestError as e:
    print(f"❌ 网络请求错误: {e}")
    
except Exception as e:
    print(f"❌ 未知错误: {e}")

print("\n" + "="*50)